//
//  SetRedLineViewController.m
//  IntelligentHousehold
//
//  Created by Chen on 2017/6/25.
//  Copyright © 2017年 Cassie. All rights reserved.
//

#import "SetRedLineViewController.h"

#import "LockOpenSetTableViewCell.h"

#import <MessageUI/MessageUI.h>//系统短信


@interface SetRedLineViewController ()<UITableViewDelegate,UITableViewDataSource,LockOpenSetTableViewCellDelegate,MFMessageComposeViewControllerDelegate>{
    NSString *msgTitle;//发送短信内容
}

/**  */
@property (nonatomic , strong) UITableView *tableView;
/**  */
@property (nonatomic , strong) NSArray *dataArray;

/**  */
@property (nonatomic , assign) BOOL redBool;

/**  */
@property (nonatomic , assign) BOOL dianBool;

@end

@implementation SetRedLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = BaseColor;
    self.navigationItem.title = @"设置红外/门磁报警";
    
    [self createData];
    
    [self createTableView];
    [self getQueryRed];
}

- (void)refreshAction{
    [self createData];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}

- (void)createData{
    self.dataArray = [NSArray array];
    self.dataArray = @[@"红外报警",@"门磁报警"];
}

- (void)createTableView{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight) style:(UITableViewStyleGrouped)];
    tableView.backgroundColor = BaseColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = 60;
    tableView.bounces = YES;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    [tableView registerNib:[UINib nibWithNibName:@"LockOpenSetTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshAction)];
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
    self.tableView = tableView;
}

- (void)lockOpenSetPassOn:(BOOL)isOne index:(NSInteger)index{
    if (index- 2000 == 0) {
        
        self.redBool = isOne;
        if (self.redBool) {//开启红外线
            msgTitle = @"openred";
            [self sendMsg];
            
        }else{//关闭红外线报警
            msgTitle = @"closered";
            [self sendMsg];
           
        }
        
        
    } else {
        self.dianBool = isOne;
        if (self.dianBool) {//开启电磁报警
            msgTitle = @"openmagnet";
            [self sendMsg];
            
        }else{//关闭电磁报警
            msgTitle = @"closemagnet";
            [self sendMsg];
            
        }

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LockOpenSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.titleImage.hidden = YES;
    cell.titleLabel.text = self.dataArray[indexPath.row];
    cell.tag = 2000+indexPath.row;
    cell.leftMargin.constant = 15;
    if (indexPath.row == 0) {
        cell.isOn = self.redBool;
    } else {
        cell.isOn = self.dianBool;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, 10)];
    view.backgroundColor = BaseColor;
    return view;
}
//设置红外电磁告警
-(void)setRedElctric:(NSString *)redOrElectric Types:(NSString *)types Command:(NSString *)command{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *url = [NSString stringWithFormat:REDELECTRIC,RealmName];
    
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:redOrElectric forKey:@"type"];//红外告警还是电磁告警  0代表是红外告警 1代表电磁告警
    [parameDic setObject:types forKey:@"types"];//关闭还是开启  0代表关闭 1代表开启
    [parameDic setObject:command forKey:@"command"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];

    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        [MBProgressHUD showText:[responseObject objectForKey:@"msg"]];
//        if ([[responseObject objectForKey:@"msg"] isEqualToString:@"success"]) {
            [self getQueryRed];
//        };
        
        NSLog(@"%@", responseObject);
    } failure:^(NSError *error) {
        
    }];

}

//查询红外电磁告警
-(void)getQueryRed{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *url = [NSString stringWithFormat:QUERYRED,RealmName];
    
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];
//    [parameDic setObject:@"17" forKey:@"user_id"];
//    [parameDic setObject:@"596886d2adf85" forKey:@"token"];
//    [parameDic setObject:@"10086" forKey:@"locknumber"];

    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        if ([[responseObject objectForKey:@"msg"] isEqualToString:@"success"]) {
            _redBool = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"redall"]].integerValue;
            _dianBool = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"electric"]].integerValue;
            [self.tableView reloadData];
            NSLog(@"%@", responseObject);
        }else{
            [MBProgressHUD showText:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"msg"]]];
        }
        
    } failure:^(NSError *error) {
        
    }];

    
}

#pragma mark -------------- 发送短信 ----------------
-(void)sendMsg{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *telStr = saveDic[@"locknumber"];
//    telStr = @"10086";

    if (telStr.length>4) {
        [self showMessageView:[NSArray arrayWithObjects:telStr, nil] title:nil body:msgTitle];
    }else{
        [MBProgressHUD showText:@"请先设置门锁号码"];
    }
    
    
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if([MFMessageComposeViewController canSendText] )
    {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"该设备不支持短信功能 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark - MFMessageComposeViewController

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (result) {
        if (MessageComposeResultSent) {//短信发送成功
            
            if ([msgTitle containsString:@"red"]) {
                [self setRedElctric:@"0" Types:[NSString stringWithFormat:@"%d",self.redBool] Command:msgTitle];
            }else{
                [self setRedElctric:@"1" Types:[NSString stringWithFormat:@"%d",self.dianBool] Command:msgTitle];
            }
            
        }
    }else{
        
        [self getQueryRed];
    }

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
